package com.taobaostore.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.taobaostore.common.ResponseCode;
import com.taobaostore.common.ServerResponse;
import com.taobaostore.dao.CategoryMapper;
import com.taobaostore.dao.ProductMapper;
import com.taobaostore.pojo.Category;
import com.taobaostore.pojo.Product;
import com.taobaostore.service.ICategoryService;
import com.taobaostore.service.IProductService;
import com.taobaostore.util.DateTimeUtil;
import com.taobaostore.util.PropertiesUtil;
import com.taobaostore.vo.ProductDetailVo;
import com.taobaostore.vo.ProductListVo;
@Service
@Primary
@Transactional
public class ProductServiceImpl implements IProductService {
	@Autowired
    private ProductMapper productMapper;
	@Autowired
	private CategoryMapper categoryMapper;
	@Autowired
	private ICategoryService iCategoryService;
	@Override
	public List<Product> listProduct() {
		return productMapper.listProduct();
	}
	@Override
	public ServerResponse<String> insertProduct(Product product) {
		try {
			productMapper.insertSelective(product);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ServerResponse.createBySuccess("新增商品信息成功!");
	}
	
	/**
	 * 新增商品
	 */
	public ServerResponse saveOrUpdateProduct(Product product) {
		if (product != null) {
			// 如果商品子图片不为空那就将第一张图片设置为主图
			if (StringUtils.isNotBlank(product.getSubImages())) {
				String[] subImageArray = product.getSubImages().split(",");
				if (subImageArray.length > 0) {
					product.setMainImage(subImageArray[0]);
				}
			}
			if (product.getId() != null) {
				System.out.println("进入更新");
                int rowCount = productMapper.updateByPrimaryKeySelective(product);
                if (rowCount == 1) {
					return ServerResponse.createBySuccess("商品更新成功!");
				}
                return ServerResponse.createByError("商品更新失败!");
			}else {
				int rowCount = productMapper.insert(product);
			    if (rowCount == 1) {
					return ServerResponse.createBySuccess("商品新增成功");
				}
			    return ServerResponse.createByError("商品新增失败");
			}
		}
		return ServerResponse.createByError("操作失败或商品参数不正确!");
	}
	
	/**
	 *设置商品状态(1.在售,2.下架,3.删除)
	 */
	public ServerResponse<String> setProductStatus(Integer productId,Integer status){
		if (null == productId || null == status) {
			return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
		}
		Product product = new Product();
		product.setId(productId);
		product.setStatus(status);
		int rowCount = productMapper.updateByPrimaryKeySelective(product);
		if (rowCount == 1) {
			return ServerResponse.createBySuccess("更新商品信息成功");
		}else {
			return ServerResponse.createByError("更新商品信息失败!");
		}
	}
	
	/**
	 *查询指定页面以及页容量的数据
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public ServerResponse<PageInfo<ProductListVo>> listProduct(Integer pageNum,Integer pageSize){
		PageHelper.startPage(pageNum, pageSize);
		List<Product> productList = productMapper.listProduct();
		List<ProductListVo> productListVos = new ArrayList<ProductListVo>();
		for (Product product : productList) {
			// 不显示被删除的元素
			productListVos.add(ProductToVo(product));
		}
		PageInfo<ProductListVo> pageInfo = new PageInfo<ProductListVo>(productListVos);
		int pageCount = productMapper.CountProduct();
		pageInfo.setPages(pageCount % pageSize==0?pageCount/pageSize:pageCount/pageSize+1);// 手动计算总页数
		System.out.println("总页数:"+pageInfo.getPages());
		ServerResponse<PageInfo<ProductListVo>> response = ServerResponse.createBySuccess(pageInfo);
		System.out.println("页面:"+response);
		return response;
	}
	
	/**
	 * 按照id查询出商品信息(用于列表)
	 * @param productId
	 * @return
	 */
	public ServerResponse<PageInfo<ProductListVo>> getProductById(int productId,Integer pageNum,Integer pageSize){
		PageHelper.startPage(pageNum, pageSize);
		List<Product> productList = Lists.newArrayList();
		productList.add(productMapper.getProductById(productId));
		if (productMapper.getProductById(productId) == null) {
			return ServerResponse.createByError("沒有找到你想要的数据");
		}
		List<ProductListVo> productListVos = new ArrayList<ProductListVo>();
		for (Product product : productList) {
			productListVos.add(ProductToVo(product));
		}
		PageInfo<ProductListVo> pageInfo = new PageInfo<ProductListVo>(productListVos);
		int pageCount = productMapper.CountProduct();
		pageInfo.setPages(pageCount % pageSize==0?pageCount/pageSize:pageCount/pageSize+1);// 手动计算总页数
		System.out.println("总页数:"+pageInfo.getPages());
		ServerResponse<PageInfo<ProductListVo>> response = ServerResponse.createBySuccess(pageInfo);
		System.out.println("页面:"+response);
		return response;
	}
	
	/**
	 * 按照id查询出商品信息(用于详情)
	 * @param productId
	 * @return
	 */
	public ServerResponse<PageInfo<ProductDetailVo>> getProductByIdDetail(int productId,Integer pageNum,Integer pageSize){
		PageHelper.startPage(pageNum, pageSize);
		List<Product> productList = Lists.newArrayList();
		productList.add(productMapper.getProductById(productId));
		if (productMapper.getProductById(productId) == null) {
			return ServerResponse.createByError("沒有找到你想要的数据");
		}
		List<ProductDetailVo> productDetailList = new ArrayList<ProductDetailVo>();
		for (Product product : productList) {
			productDetailList.add(ProductToDetailVo(product));
		}
		PageInfo<ProductDetailVo> pageInfo = new PageInfo<ProductDetailVo>(productDetailList);
		int pageCount = productMapper.CountProduct();
		pageInfo.setPages(pageCount % pageSize==0?pageCount/pageSize:pageCount/pageSize+1);// 手动计算总页数
		System.out.println("总页数:"+pageInfo.getPages());
		ServerResponse<PageInfo<ProductDetailVo>> response = ServerResponse.createBySuccess(pageInfo);
		System.out.println("页面:"+response);
		return response;
	}
	
	/**
	 * 按照名称模糊查询商品信息
	 * @param productName
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public ServerResponse<PageInfo<ProductListVo>> listProductByName(String productName,Integer pageNum,Integer pageSize){
		PageHelper.startPage(pageNum, pageSize);
		List<Product> productList = productMapper.listProductByName(productName);
		if (productList.size() == 0) {
			return ServerResponse.createByError("沒有找到你想要的数据");
		}
		List<ProductListVo> productListVos = new ArrayList<ProductListVo>();
		for (Product product : productList) {
			// 不显示被删除的元素
			productListVos.add(ProductToVo(product));
		}
		PageInfo<ProductListVo> pageInfo = new PageInfo<ProductListVo>(productListVos);
		int pageCount = productMapper.CountProduct();
		pageInfo.setPages(pageCount % pageSize==0?pageCount/pageSize:pageCount/pageSize+1);// 手动计算总页数
		System.out.println("总页数:"+pageInfo.getPages());
		ServerResponse<PageInfo<ProductListVo>> response = ServerResponse.createBySuccess(pageInfo);
		System.out.println("页面:"+response);
		return response;
	}
	
	/**
	 * 前台返回商品详细信息
	 * @param productId
	 * @return
	 */
	public ServerResponse<ProductDetailVo> getProductDetail(Integer productId){
		if (productId == null) {
			return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
		}
		Product product = productMapper.getProductIdStatus(productId);
		if (product == null) {
			return ServerResponse.createByError("产品已被下架或者删除!");
		}
	    ProductDetailVo productDetailVo = ProductToDetailVo(product);
	    return ServerResponse.createBySuccess(productDetailVo);
	}
	 
	/**
	 * 返回用户查找的商品集合
	 * @param keyword
	 * @param categoryId
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public ServerResponse<PageInfo> getProductByKeywordCategory(String keyword,Integer categoryId,int pageNum,int pageSize){
		if (StringUtils.isBlank(keyword) && categoryId == null) {
			return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(),ResponseCode.ILLEGAL_ARGUMENT.getDESC());
		}
		if (null == categoryId) {
			categoryId = 0;
		}
		// 遍历出该节点下所有子节点分类
	    List<Integer> categoryIdList = new ArrayList<Integer>();
		Category category = categoryMapper.getCategoryById(categoryId);
		if (category == null && StringUtils.isBlank(keyword)) {
			// 没有找到指定分类也没有传入关键词
			PageHelper.startPage(pageNum, pageSize);
			List<ProductListVo> productListVos = Lists.newArrayList();
			PageInfo pageInfo = new PageInfo(productListVos);
			return ServerResponse.createBySuccess(pageInfo);
		}
		categoryIdList = (List<Integer>) iCategoryService.selectCategoryAndDeepChildrenByrenId(categoryId).getData();
		keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
		
		// 分页
		PageHelper.startPage(pageNum, pageSize);
		// 查出指定类型或指定关键字的商品信息
		List<Product> list = productMapper.selectByNameAndCategoryIds(StringUtils.isBlank(keyword)?null:keyword,categoryIdList.size()==0?null:categoryIdList);
		List<ProductListVo> productListVos = Lists.newArrayList();
		for (Product product : list) {
			productListVos.add(ProductToVo(product));
		}
		PageInfo pageInfo = new PageInfo(productListVos);
		return ServerResponse.createBySuccess(pageInfo);
	}
	
	
	/**
	 * 將product對象转换为Vo对象(value Object)
	 * @param product
	 * @return
	 */
	private ProductListVo ProductToVo(Product product) {
		ProductListVo productListVo  = new ProductListVo();
		productListVo.setId(product.getId());
		productListVo.setName(product.getName());
		productListVo.setCategoryId(product.getCategoryId());
		productListVo.setStatus(product.getStatus());
		productListVo.setStock(product.getStock());
		productListVo.setCreateTime(DateTimeUtil.DateTostr(product.getCreateTime()));
		productListVo.setImage_Main(product.getMainImage());
		// 处理状态信息
		if (product.getStatus()==1) {
			productListVo.setStatusName("在售");
		}else if (product.getStatus()==2) {
			productListVo.setStatusName("下架");
		}else if (product.getStatus()==3) {
			productListVo.setStatusName("刪除");
		}
		productListVo.setCategoryName(categoryMapper.getCategoryById(product.getCategoryId()).getName());
		return productListVo;
	}
	
	/**
	 * 将product对象转换为商品详情
	 * @param product
	 * @return
	 */
	private ProductDetailVo ProductToDetailVo(Product product){
        ProductDetailVo productDetailVo = new ProductDetailVo();
        productDetailVo.setId(product.getId());
        productDetailVo.setSubtitle(product.getSubtitle());
        productDetailVo.setPrice(product.getPrice());
        productDetailVo.setMainImage(product.getMainImage());
        String[] subImages = product.getSubImages().split(",");
        productDetailVo.setSubImages(subImages);
        productDetailVo.setCategoryId(product.getCategoryId());
        productDetailVo.setDetail(product.getDetail());
        productDetailVo.setName(product.getName());
        productDetailVo.setStatus(product.getStatus());
        productDetailVo.setStock(product.getStock());
        Category category = categoryMapper.getCategoryById(product.getCategoryId());
        if(category == null){
            productDetailVo.setParentCategoryId(0);//默认根节点
        }else{
            productDetailVo.setParentCategoryId(category.getParentId());
        }
        productDetailVo.setCreateTime(DateTimeUtil.DateTostr(product.getCreateTime()));
        productDetailVo.setUpdateTime(DateTimeUtil.DateTostr(product.getUpdateTime()));
        return productDetailVo;
    }
}
